package com.deewin.study.lock;

import java.util.concurrent.TimeUnit;

/**
 * 使用 synchronize来同步
 *
 */
public class MySync {

    public static void main(String[] args) throws InterruptedException {
        TetsClass1 tc = new TetsClass1();
        for(int i=0;i<5;i++){
            Thread t = new Thread(new MyRun1(tc));
            t.start();
           t.join();//不加join，线程还没执行完成，就去执行 tc.sum(); 这样的话，这些线程都是串行执行了，都可以不用加synchronize了
                    //应该想想其他办法，让这些线程都执行完再去 tc.sum（）；
        }
        tc.sum();
    }

}

class MyRun1 implements Runnable{

    TetsClass1 tc;

    MyRun1(){}

    MyRun1(TetsClass1 tc){
        this.tc = tc;
    }

    @Override
    public void run() {
        try {
            tc.dosometing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


class TetsClass1{

    int[] from = {12,454,54,12,5};

    int[] to = {434,454,12,54,34};

    public synchronized void  dosometing() throws InterruptedException {
        System.out.println("进来的线程是："+ Thread.currentThread().getName());
        for(int i=0;i<from.length;i++) {
            from[i] -=  5;
            TimeUnit.SECONDS.sleep(1);
            to[i] +=  5;
        }
    }

    public  void sum(){
        System.out.println("原理的总数：");
        int f = 12+454+54+12+5;
        int t = 434+454+12+54+34;
        System.out.println("form:"+f);
        System.out.println("to:"+t);
        System.out.println("total="+(f+t));
        int formsum=0;
        for (int i=0;i<from.length;i++){
            formsum += from[i];
        }
        int tosum=0;
        for (int i=0;i<to.length;i++){
            tosum += to[i];
        }
        System.out.println("后来的sum：");
        System.out.println("form  "+formsum);
        System.out.println("tosum  "+tosum);
        System.out.println("total="+(formsum+tosum));
    }
}